<template>
  <div class="page-wrapper">
    <div class="flex1">
        <el-scrollbar style="width: 100%;" :height="srollHeight" :min-size="40">
            <div class="flex flexL mb20">
                <div class="mr10">盘点批次选择</div>
                <div>
                    <el-select v-model="choosTime" allow-create placeholder="请选择" style="width: 230px;" @change="handleChangeUser">
                        <el-option
                        v-for="item in choosTimeList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                        />
                    </el-select>
                </div>
            </div>
            <div class="flex1 flex">
                <div style="width: 100px;display: flex;">
                    <div class="flex">
                        <div style="width: 100px;">
                            <div class="hed">产品</div>
                            <div class="bod bodl" :style="{color: item.color}" v-for="item,i in proList" :key="i">{{ item.attr.two_name }} - {{ item.attr_name }}</div>
                            <div class="bod bodl bold textC">汇总</div>
                        </div>
                    </div>
                </div>
                <div style="width: calc(100% - 100px)">
                    <el-scrollbar always style="width: 100%;" height="auto" :min-size="40">
                        <div class="flex pb20">
                            <div style="width: 120px;flex-shrink: 0;" v-for="tim,t in dateList" :key="t">
                                <div class="hed" @click="addDate(tim.type)">
                                    <div>
                                        <div class="textC pointer" v-if="tim.type == 'add'">+新增盘存</div>
                                        <div class="textC" v-else-if="tim.type == 'chae'">总数</div>
                                        <div class="textC" v-else-if="tim.type == 'user'">{{ tim.user }}</div>
                                        <div class="textC" v-else>
                                            <el-date-picker
                                                style="width: 110px;"
                                                size="small"
                                                v-model="tim.value"
                                                type="date"
                                                placeholder="请选择日期"
                                                format="YYYY-MM-DD"
                                                value-format="YYYY-MM-DD"
                                                :disabled="tim.dis"
                                            />
                                        </div>
                                    </div>
                                </div>
                                <div class="bod" v-for="item,i in tim.dataList" :key="i" v-if="tim.type != 'add'" @dblclick="editItem(item, tim)">
                                    <span v-if="tim.dis&&tim.type != 'chae'&&tim.type != 'user'" class="c999">{{item.ptype==1?'盘存库存':'到货库存'}}：</span>
                                    <span v-if="tim.dis" :style="{'padding-left': (tim.type=='chae'||tim.type=='user') ? '40px' : ''}">{{ item.value }}</span>
                                    <el-input size="small" v-else v-model="item.value" type="number" placeholder="输入盘存数量"></el-input>
                                </div>
                                <div class="bod textC" v-if="tim.type != 'add'">
                                    <span>{{ tim.total_num }}</span>
                                </div>
                                <div v-if="tim.type != 'add' && !tim.dis" style="padding-top: 4px;">
                                    <el-button size="small" type="default" @click="del(t)">删除</el-button>
                                    <el-button size="small" type="primary" @click="save(t)">保存</el-button>
                                </div>
                            </div>
                        </div>
                    </el-scrollbar>
                </div>
            </div>
        </el-scrollbar>
    </div>
  </div>
</template>

<script setup lang="ts">
import { addCheck, getCheckList, getchecktime, getInventoryItem, getProduct } from '@/api/api';
import { elMsg } from '@/utils/message';
import { timeResetDate } from '@/utils/tool';
import { ElMessageBox } from 'element-plus';
import { reactive, ref, computed,onMounted } from 'vue'

const srollHeight = ref(0);
const proList = ref([]);
const choosTime = ref('');
const choosTimeList = ref([]);
const dateList = ref([{
    type: 'add'
}]);
const order_sns = ref([]);
onMounted(() => {
    srollHeight.value = document.documentElement.clientHeight - 150;
    init();
})
// js 数组每两条数据中间插入一条数据
const insertBetween = (arr, newElement) => {
  return arr.reduce((acc, item, index) => {
    acc.push(item);
    // 如果不是数组的最后一个元素，插入新元素
    if (index < arr.length - 1) {
      if(Array.isArray(newElement)){
        acc.push(...newElement);
      }else{
        acc.push(newElement);
      }
    }
    return acc;
  }, []);
}
const handleChangeUser = (e) => {
     console.log(choosTime.value);
     const item = choosTimeList.value.find(i => i.value==e)
    if(item){
        order_sns.value = item.list;
        getData();
    }
}
const init = async () => {
    const newData = await getProduct(2) // 新款染发夹id是2
    const pcData = await getchecktime() // 盘存日历分组
    newData.data.sku.forEach(element => {
        if(element.attr.two_name == "哑光"){
            element.color = '#000';
        }
        if(element.attr.two_name == "珠光"){
            element.color = '#EB809C';
        }
        if(element.attr.two_name == "荧光"){
            element.color = '#5EADCB';
        }
    });
    proList.value = newData.data.sku;
    // proList.value = newData.data.sku.sort((a,b)=>a.id-b.id);
    pcDataGroup(pcData.data);
    // console.log(newData.data.sku);
}
const pcDataGroup = (pcData) => {
    // console.log(pcData);
    const timeData = [];
    pcData.forEach(el => {
        el.check_time = el.check_time.slice(0,10);
        const listitem = timeData.find(i => i.order_sn == el.order_sn)
        if(listitem){
            
        }else{
            timeData.push({
                check_time: el.check_time,
                order_sn: el.order_sn,
            })
        }
    });
    const oldtlist = groupByTwo(timeData);
    const tlist = oldtlist.filter(i => i.length == 2);
    // console.log(tlist);
    choosTimeList.value = tlist.map((item, i) => {
        let onlyDept = false;
        if(new Date(item[0].check_time.replace(/-/g,'/')).getTime() > 1747744655000){
            onlyDept = true;
        }
        return {
            value: i+1,
            onlyDept: onlyDept,
            label: `${item[0].check_time} 至 ${item[1].check_time}`,
            list: [item[0].order_sn,item[1].order_sn]
        }
    })
    if(choosTimeList.value.length){
        choosTime.value = choosTimeList.value[choosTimeList.value.length-1].value;
        order_sns.value = choosTimeList.value[choosTimeList.value.length-1].list;
    }
    console.log(choosTimeList.value);
    getData();
}
const groupByTwo = (arr) => {
    const result = [];
    for (let i = 0; i < arr.length; i += 2) {
        result.push(arr.slice(i, i + 2));
    }
    return result;
}
const getData = () => {
    if(order_sns.value.length<2){
        return;
    }
    const choosTimeItem = choosTimeList.value.find(i => i.value == choosTime.value);
    const onlyDept = choosTimeItem?.onlyDept || false;
    console.log('onlyDept', onlyDept);
    dateList.value = [];
    getCheckList({
        order_sn: order_sns.value
    }).then((result) => {
        // console.log(result.data);
        // const firstdata = result.data.sort((a,b)=>a.id-b.id);
        // proList.value.forEach(item => {
        //     const pitem = result.data.find(i => i.pro_id == item.id);
        //     console.log('pitem', pitem);
        //     if(pitem){
        //         pitem.sort = item.sort;
        //     }
        // })
        // console.log(JSON.parse(JSON.stringify(proList.value)));
        // console.log(JSON.parse(JSON.stringify(result.data)));
        const firstdata = result.data;
        // 根据check_time分组
        const chaelist = [];
        let list = [];
        firstdata.forEach(el => {
            el.check_time = el.check_time.slice(0,10);
            const listitem = list.find(i => i.value == el.check_time)
            if(listitem){
                listitem.dataList.push({
                    dataid: el.id,
                    id: el.pro_id,
                    ptype: el.type,
                    inventory: el.inventory,
                    value: el.check_num,
                })
            }else{
                list.push({
                    type: 'time',
                    dis: true,
                    ptype: el.type,
                    dataList:[{
                        dataid: el.id,
                        id: el.pro_id,
                        ptype: el.type,
                        inventory: el.inventory,
                        value: el.check_num,
                    }],
                    value: el.check_time
                })
            }
        });
        list.sort((a,b) => new Date(a.value.replace(/-/ig,'/')).getTime() - new Date(b.value.replace(/-/ig,'/')).getTime());
        list.forEach(item => {
            item.dataList.forEach(etem => {
                const proitem = proList.value.find(i => i.id == etem.id);
                if(proitem){
                    etem.sort = proitem.sort;
                }
            })
            item.dataList = item.dataList.sort((a,b)=>a.sort-b.sort)
        })
        console.log(JSON.parse(JSON.stringify(list)));
        // return;
        list.forEach((el, i) => {
            el.total_num = el.dataList.reduce((to,itm) => {
                return to + Number(itm.value)
            }, 0)
            el.dataList = el.dataList;//.sort((a,b)=>a.id-b.id);
            chaelist.push(el);
        })
        const addlist = onlyDept ? [{
            type: 'chae',
            dis: true,
            dataList: proList.value.map(item => {
                return {
                    id: item.id,
                    inventory: item.inventory,
                    value: '',
                }
            })
        },{
            type: 'user',
            user: '1688',
            dis: true,
            dataList: proList.value.map(item => {
                return {
                    id: item.id,
                    inventory: item.inventory,
                    value: '',
                }
            })
        },{
            type: 'user',
            user: '老金',
            dis: true,
            dataList: proList.value.map(item => {
                return {
                    id: item.id,
                    inventory: item.inventory,
                    value: '',
                }
            })
        },{
            type: 'user',
            user: '小刚',
            dis: true,
            dataList: proList.value.map(item => {
                return {
                    id: item.id,
                    inventory: item.inventory,
                    value: '',
                }
            })
        }] : [{
            type: 'chae',
            dis: true,
            dataList: proList.value.map(item => {
                return {
                    id: item.id,
                    inventory: item.inventory,
                    value: '',
                }
            })
        },{
            type: 'user',
            user: '1688',
            dis: true,
            dataList: proList.value.map(item => {
                return {
                    id: item.id,
                    inventory: item.inventory,
                    value: '',
                }
            })
        },{
            type: 'user',
            user: '老金',
            dis: true,
            dataList: proList.value.map(item => {
                return {
                    id: item.id,
                    inventory: item.inventory,
                    value: '',
                }
            })
        },{
            type: 'user',
            user: '小刚',
            dis: true,
            dataList: proList.value.map(item => {
                return {
                    id: item.id,
                    inventory: item.inventory,
                    value: '',
                }
            })
        },{
            type: 'user',
            user: '叶宜智',
            dis: true,
            dataList: proList.value.map(item => {
                return {
                    id: item.id,
                    inventory: item.inventory,
                    value: '',
                }
            })
        },{
            type: 'user',
            user: '李博',
            dis: true,
            dataList: proList.value.map(item => {
                return {
                    id: item.id,
                    inventory: item.inventory,
                    value: '',
                }
            })
        }]
        const relylist = insertBetween(chaelist, addlist);
        relylist.push({
            type: 'add',
        })
        relylist.forEach((el, i) => {
            if(el.type == 'chae'){
                if(onlyDept){
                    // 用前后来计算数量
                    const startItem = relylist[i-1];
                    const endItem = relylist[i+4];
                    el.dataList.forEach((ele, ei) => {
                        ele.value = startItem.dataList[ei].value - endItem.dataList[ei].value;
                    });
                    el.total_num = el.dataList.reduce((to,itm) => {
                        return to + Number(itm.value)
                    }, 0)
                    getUserData(startItem.value, endItem.value, i, onlyDept);
                }else{
                    // 用前后来计算数量
                    const startItem = relylist[i-1];
                    const endItem = relylist[i+6];
                    el.dataList.forEach((ele, ei) => {
                        ele.value = startItem.dataList[ei].value - endItem.dataList[ei].value;
                    });
                    el.total_num = el.dataList.reduce((to,itm) => {
                        return to + Number(itm.value)
                    }, 0)
                    getUserData(startItem.value, endItem.value, i, onlyDept);
                }
            }
        });
        dateList.value = relylist;
        console.log(relylist);
        // 获取客户的出库记录
    }).catch((err) => {
        console.log(err);
    });
}
const getUserData = (start, end, chaeIndex, onlyDept) => {
    // 开始时间要加一天
    const startXf = new Date(start.replace(/-/ig,'/') + ' 00:00:00').getTime()+86400000;
    const startTime = timeResetDate(startXf);
    const endTime = end + ' 23:59:59';
    console.log(startTime, endTime, chaeIndex);
    let task = [];
    if(choosTime.value>1){
        if (onlyDept) {
            task = [
                getInventoryItem({
                    productName: '心型染发夹',
                    department_name: '成长脉搏',
                    start: startTime,
                    end: endTime,
                    type: 2,
                }),
                getInventoryItem({
                    productName: '心型染发夹',
                    department_name: '金总',
                    start: startTime,
                    end: endTime,
                    type: 2,
                }),
                getInventoryItem({
                    productName: '心型染发夹',
                    department_name: '小刚',
                    start: startTime,
                    end: endTime,
                    type: 2,
                }),
            ]
        } else {
            task = [
                getInventoryItem({
                    productName: '心型染发夹',
                    department_name: '成长脉搏',
                    start: startTime,
                    end: endTime,
                    type: 2,
                }),
                getInventoryItem({
                    productName: '心型染发夹',
                    department_name: '金总',
                    start: startTime,
                    end: endTime,
                    type: 2,
                }),
                getInventoryItem({
                    productName: '心型染发夹',
                    department_name: '小刚',
                    start: startTime,
                    end: endTime,
                    type: 2,
                }),
                getInventoryItem({
                    productName: '心型染发夹',
                    customer_name: '叶宜智',
                    start: startTime,
                    end: endTime,
                    type: 2,
                }),
                getInventoryItem({
                    productName: '心型染发夹',
                    customer_name: '李博',
                    start: startTime,
                    end: endTime,
                    type: 2,
                }),
            ]
        }
    }else{
        task = [
            getInventoryItem({
                productName: '心型染发夹',
                customer_name: '1688成长脉搏工厂店',
                start: startTime,
                end: endTime,
                type: 2,
            }),
            getInventoryItem({
                productName: '心型染发夹',
                customer_name: '老金',
                start: startTime,
                end: endTime,
                type: 2,
            }),
            getInventoryItem({
                productName: '心型染发夹',
                customer_name: '小刚脸彩',
                start: startTime,
                end: endTime,
                type: 2,
            }),
            getInventoryItem({
                productName: '心型染发夹',
                customer_name: '叶宜智',
                start: startTime,
                end: endTime,
                type: 2,
            }),
            getInventoryItem({
                productName: '心型染发夹',
                customer_name: '李博',
                start: startTime,
                end: endTime,
                type: 2,
            }),
        ]
    }
    Promise.all(task).then((result) => {
        dateList.value[chaeIndex+1].dataList.forEach((ele, ei) => {
            // 找到对应ID的产品出库记录
            const proList = result[0].data.filter(i => i.product_id==ele.id);
            // 如果总数是0，那么赋值为0
            const totalItem = dateList.value[chaeIndex].dataList.find(i => i.id == ele.id);
            if(totalItem.value <= 0){
                ele.value = 0;
            }else{
                ele.value = proList.reduce((to,itm) => {
                    return to + Number(itm.quantity)
                }, 0)
            }
        });
        dateList.value[chaeIndex+1].total_num = dateList.value[chaeIndex+1].dataList.reduce((to,itm) => {
            return to + Number(itm.value)
        }, 0)
        dateList.value[chaeIndex+2].dataList.forEach((ele, ei) => {
            // 找到对应ID的产品出库记录
            const proList = result[1].data.filter(i => i.product_id==ele.id);
            // 如果总数是0，那么赋值为0
            const totalItem = dateList.value[chaeIndex].dataList.find(i => i.id == ele.id);
            if(totalItem.value <= 0){
                ele.value = 0;
            }else{
                ele.value = proList.reduce((to,itm) => {
                    return to + Number(itm.quantity)
                }, 0)
            }
        });
        dateList.value[chaeIndex+2].total_num = dateList.value[chaeIndex+2].dataList.reduce((to,itm) => {
            return to + Number(itm.value)
        }, 0)
        dateList.value[chaeIndex+3].dataList.forEach((ele, ei) => {
            // 找到对应ID的产品出库记录
            const proList = result[2].data.filter(i => i.product_id==ele.id);
            // 如果总数是0，那么赋值为0
            const totalItem = dateList.value[chaeIndex].dataList.find(i => i.id == ele.id);
            if(totalItem.value <= 0){
                ele.value = 0;
            }else{
                ele.value = proList.reduce((to,itm) => {
                    return to + Number(itm.quantity)
                }, 0)
            }
        });
        dateList.value[chaeIndex+3].total_num = dateList.value[chaeIndex+3].dataList.reduce((to,itm) => {
            return to + Number(itm.value)
        }, 0)
        if(!onlyDept){
            dateList.value[chaeIndex+4].dataList.forEach((ele, ei) => {
                // 找到对应ID的产品出库记录
                const proList = result[3].data.filter(i => i.product_id==ele.id);
                // 如果总数是0，那么赋值为0
                const totalItem = dateList.value[chaeIndex].dataList.find(i => i.id == ele.id);
                if(totalItem.value <= 0){
                    ele.value = 0;
                }else{
                    ele.value = proList.reduce((to,itm) => {
                        return to + Number(itm.quantity)
                    }, 0)
                }
            });
            dateList.value[chaeIndex+4].total_num = dateList.value[chaeIndex+4].dataList.reduce((to,itm) => {
                return to + Number(itm.value)
            }, 0)
            dateList.value[chaeIndex+5].dataList.forEach((ele, ei) => {
                // 找到对应ID的产品出库记录
                const proList = result[4].data.filter(i => i.product_id==ele.id);
                // 如果总数是0，那么赋值为0
                const totalItem = dateList.value[chaeIndex].dataList.find(i => i.id == ele.id);
                if(totalItem.value <= 0){
                    ele.value = 0;
                }else{
                    ele.value = proList.reduce((to,itm) => {
                        return to + Number(itm.quantity)
                    }, 0)
                }
            });
            dateList.value[chaeIndex+5].total_num = dateList.value[chaeIndex+5].dataList.reduce((to,itm) => {
                return to + Number(itm.value)
            }, 0)
        }
    }).catch((err) => {
        console.log(err);
    });
}
const addDate = (type) => {
    if(type == 'add'){
        dateList.value.splice(dateList.value.length-1, 1);
        dateList.value.push({
            type: 'time',
            dis: false,
            dataList: proList.value.map(item => {
                return {
                    id: item.id,
                    inventory: item.inventory,
                    value: item.inventory,
                }
            }),
            value: timeResetDate('', true),
        })

        dateList.value.push({
            type: 'add',
        })
    }
}
const del = (t) => {
    dateList.value.splice(t, 1);
}
const save = (index) => {
    const adddata = dateList.value[index];
    console.log(adddata);
    if(!adddata.value){
        elMsg('请填写盘存日期', 'error');
        return;
    }
    // if(dateList.value.filter(i=>i.value == adddata.value).length > 1){
    //     elMsg('日期重复', 'error');
    //     return;
    // }
    const contents = adddata.dataList.map(item => {
        return {
            pro_id: item.id,
            remark: '',
            inventory: Number(item.inventory),
            check_num: Number(item.value),
            check_time: adddata.value,
        }
    })
    let params = {
        contents: JSON.stringify(contents),
    }
    addCheck(params).then((result) => {
        elMsg('添加成功', 'success');
        dateList.value = [];
        getData();
    }).catch((err) => {
        
    });
}
const editItem = (item, tim) => {
    if(tim.type == 'chae'||tim.type == 'user') return;
    ElMessageBox.prompt('请输入调整后的数量', '调整数量', {
        confirmButtonText: '提交',
        cancelButtonText: '关闭',
        inputType: 'number',
        inputValue: item.value
    })
        .then(({ value }) => {
            addCheck({
                id: item.dataid,
                check_num: Math.floor(value)
            }).then((result) => {
                elMsg('已调整', 'success')
                dateList.value = [];
                getData();
            }).catch((err) => {
                
            });
        })
        .catch(() => {
        // .
    })
}
</script>

<style lang="scss" scoped>
.table{
    border-collapse: collapse;
}
.exp {
    width: 70px;
    height: 30px;
}
.greeItem{
    background: #95F204;
}
.orgeItem{
    background: #F59A23;
}
.blueItem{
    background: #02A7F0;
}
.hed {
    height: 26px;
    background-color: #EEEEEE;
    display: flex;
    justify-content: center;
    align-items: center;
    border-top: 1px solid #dddddd;
    border-bottom: 1px solid #dddddd;
    box-sizing: border-box;
    border-right: 1px solid #dddddd;
    border-left: 1px solid #dddddd;
    padding-left: 5px;
}
.bod {
    height: 26px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    border-bottom: 1px solid #dddddd;
    box-sizing: border-box;
    border-right: 1px solid #dddddd;
    position: relative;
    padding-left: 5px;
    &>div {
        width: 100%;
        height: 100%;
    }
}
.textC {
    justify-content: center;
}
.bodl{
    border-left: 1px solid #dddddd;
}
:deep(){
    .el-scrollbar__bar{
        height: 12px;
    }
}
.showorder {
    position: absolute;
    top: 5px;
    left: 5px;
    height: 60px !important;
    // background: #02A7F0;
    z-index: 9;
    border-radius: 4px;
    color: #fff;
    font-size: 12px;
    padding: 5px;
    box-sizing: border-box;
    box-shadow: 0 0 5px #888888;
    .pre_lease_days{
        display: inline-block;
        margin-left: 10px;
        margin-right: 10px;
        padding-bottom: 1px;
        border-bottom: 2px solid #fff;
    }
}
</style>